package com.longcai.controller.homegood;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.longcai.bean.ApiResult;
import com.longcai.entity.customer.ClyjUser;
import com.longcai.entity.homegood.ClyjGoodsHomepage;
import com.longcai.entity.homegood.ClyjGoodsSpec;
import com.longcai.entity.homegood.ClyjShoppingCart;
import com.longcai.service.homegood.ClyjGoodsHomepageService;
import com.longcai.service.homegood.ClyjGoodsSpecService;
import com.longcai.service.homegood.ClyjShoppingCartService;
import com.longcai.util.TokenUtils;
import com.longcai.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 购物车 前端控制器
 * </p>
 *
 * @author LWK
 * @since 2019-04-09
 */
@Controller
@RequestMapping("/clyjShoppingCart")
public class ClyjShoppingCartController {

    @Autowired
    ClyjShoppingCartService cartService;
    @Autowired
    ClyjGoodsHomepageService goodsService;
    @Autowired
    ClyjGoodsSpecService specService;
    @Autowired
    private TokenUtils tokenUtils;

    /**
     * 加入购物车
     *
     * @param params
     * @return
     */
    @RequestMapping("/addCart")
    @ResponseBody
    public ApiResult addCart(@RequestBody JSONObject params) {
        String token = params.getString("token");
        if (token == null || "".equals(token)) {
            return ApiResult.fail("您好，你的账号已登陆失效，请重新登陆！");
        }
        ClyjUser clyjUser = tokenUtils.Itoken(token);
        if (clyjUser == null) {
            return ApiResult.fail("您好，你的账号已登陆失效，请重新登陆！");
        }
        //获取当前用户id
        String userId = clyjUser.getUserId();
        //商品id
        String goodsid = params.getString("goodsId");
        //商品数量
        String amount = params.getString("amount");
        //商品规格
        String specId = params.getString("specId");
        //商品购买价格
        String goodsPrice = params.getString("goodsPrice");
        //商品购买所需零钱
        String goodsPocket = params.getString("goodsPocket");
        //商品购买所需积分
        String goodsIntegration = params.getString("goodsIntegration");
        //购物车类型
        String cartType = params.getString("cartType");
        //店铺id
        String shopId = params.getString("shopId");

        try {
            if (amount == null || amount == "") {
                return ApiResult.fail("商品数量不能为空");
            }
            if (cartType == null || cartType == "") {
                return ApiResult.fail("购物车类型不能为空");
            }
            if (cartType.equals("2") && (shopId == null || shopId.equals(""))) {
                return ApiResult.fail("店铺id不能为空");
            }
            if (goodsPrice == null || goodsPrice == "") {
                goodsPrice = "0";
            }
            if (goodsPocket == null || goodsPocket == "") {
                goodsPocket = "0";
            }
            if (goodsIntegration == null || goodsIntegration == "") {
                goodsIntegration = "0";
            }
            //根据用户id和商品id查询购物车表
            QueryWrapper<ClyjShoppingCart> w = new QueryWrapper<ClyjShoppingCart>();
            w.eq("user_id", userId);
            w.eq("goods_id", goodsid);
            List<ClyjShoppingCart> selectList = cartService.selectList(w);
            //如果存在当前商品，数量相加
            if (selectList!=null && selectList.size() > 0 && selectList.get(0).getSpecId().equals(specId)) {
                int amountsum = Integer.valueOf(amount) + selectList.get(0).getAmount();
                selectList.get(0).setAmount(amountsum);
                selectList.get(0).setGoodsPrice(new BigDecimal(goodsPrice).multiply(new BigDecimal(amountsum)));
                selectList.get(0).setGoodsPocket(new BigDecimal(goodsPocket).multiply(new BigDecimal(amountsum)));
                selectList.get(0).setGoodsIntegration(new BigDecimal(goodsIntegration).multiply(new BigDecimal(amountsum)));
                cartService.updateById(selectList.get(0));
                return ApiResult.success();
            }
            //如果不存在，则新增商品
            ClyjShoppingCart cart = new ClyjShoppingCart();
            cart.setCreateTime(LocalDateTime.now());
            cart.setGoodsId(goodsid);
            cart.setAmount(Integer.valueOf(amount));
            cart.setGoodsPrice(new BigDecimal(goodsPrice).multiply(new BigDecimal(amount)));
            cart.setGoodsPocket(new BigDecimal(goodsPocket).multiply(new BigDecimal(amount)));
            cart.setGoodsIntegration(new BigDecimal(goodsIntegration).multiply(new BigDecimal(amount)));
            cart.setId(UUIDUtil.uuid());
            cart.setUserId(userId);
            cart.setSpecId(specId);
            cart.setCartType(cartType);
            cart.setShopId(shopId);
            cartService.insert(cart);
            return ApiResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.fail(e.getMessage());
        }
    }

    /**
     * 删除购物车
     *
     * @param params
     * @return
     */
    @RequestMapping("/delCart")
    @ResponseBody
    public ApiResult delCart(@RequestBody JSONObject params) {
        String token = params.getString("token");
        if (token == null || "".equals(token)) {
            return ApiResult.fail("您好，你的账号已登陆失效，请重新登陆！");
        }
        ClyjUser clyjUser = tokenUtils.Itoken(token);
        if (clyjUser == null) {
            return ApiResult.fail("您好，你的账号已登陆失效，请重新登陆！");
        }
        //获取当前用户id
        String userId = clyjUser.getUserId();
        //商品id
        String goodsid = params.getString("goodsId");
        //商品数量
        String amount = params.getString("amount");
        //购物车类型
        String cartType = params.getString("cartType");
        //店铺id
        String shopId = params.getString("shopId");
        try {
            if (amount == null || amount == "") {
                return ApiResult.fail("商品数量不能为空");
            }
            if (cartType == null || cartType == "") {
                return ApiResult.fail("购物车类型不能为空");
            }
            if (cartType.equals("2") && (shopId == null || shopId.equals(""))) {
                return ApiResult.fail("店铺id不能为空");
            }
            //根据用户id和商品id查询购物车表
            QueryWrapper<ClyjShoppingCart> w = new QueryWrapper<ClyjShoppingCart>();
            w.eq("user_id", userId);
            w.eq("goods_id", goodsid);
            List<ClyjShoppingCart> selectList = cartService.selectList(w);
            //如果存在当前商品，数量相减
            if (selectList.size() > 0) {
                int amountsum = selectList.get(0).getAmount() - Integer.valueOf(amount);
                if (amountsum <= 0) {
                    //删除数据
                    cartService.delete(w);
                    return ApiResult.success();
                }
                selectList.get(0).setAmount(amountsum);
                BigDecimal divide = new BigDecimal(amountsum).divide(new BigDecimal(Integer.valueOf(amount) + amountsum));
                selectList.get(0).setGoodsPrice(selectList.get(0).getGoodsPrice().multiply(divide));
                selectList.get(0).setGoodsPocket(selectList.get(0).getGoodsPocket().multiply(divide));
                selectList.get(0).setGoodsIntegration(selectList.get(0).getGoodsIntegration().multiply(divide));
                cartService.updateById(selectList.get(0));
                return ApiResult.success();
            }
            //如果不存在，则直接返回
            return ApiResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.fail(e.getMessage());
        }
    }

    /**
     * 展示购物车
     *
     * @param params
     * @return
     */
    @RequestMapping("/showCart")
    @ResponseBody
    public Map<String, Object> showCart(@RequestBody JSONObject params) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String token = params.getString("token");
        if (token == null || token.equals("")) {
            resultMap.put("code", "fail");
            resultMap.put("errorMsg", "请先登录");
            return resultMap;
        }
        ClyjUser clyjUser = tokenUtils.Itoken(token);
        if (clyjUser == null) {
            resultMap.put("code", "fail");
            resultMap.put("errorMsg", "登录已过期");
            return resultMap;
        }
        //获取当前用户id
        String userId = clyjUser.getUserId();
        //购物车类型
        String cartType = params.getString("cartType");
        //店铺id
        String shopId = params.getString("shopId");
        try {
            QueryWrapper<ClyjShoppingCart> w = new QueryWrapper<ClyjShoppingCart>();
            if (cartType == null || cartType == "") {
                resultMap.put("errorMsg", "购物车类型不能为空");
                return resultMap;
            }
            if (cartType.equals("2") && (shopId == null || shopId.equals(""))) {
                resultMap.put("errorMsg", "店铺id不能为空");
                return resultMap;
            }
            if (cartType.equals("2")) {
                w.eq("shop_id", shopId);
            }
            //根据用户id和商品id查询购物车表
            w.eq("user_id", userId);
            w.eq("cart_type", cartType);
            List<ClyjShoppingCart> selectList = cartService.selectList(w);
            for (ClyjShoppingCart clyjShoppingCart : selectList) {
                //根据商品id查询商品详情
                QueryWrapper<ClyjGoodsHomepage> w2 = new QueryWrapper<ClyjGoodsHomepage>();
                String goodsId = clyjShoppingCart.getGoodsId();
                w2.eq("goods_id", goodsId);
                List<ClyjGoodsHomepage> selectList2 = goodsService.selectList(w2);
                if (selectList2.size() == 0) {
                    continue;
                }
                ClyjGoodsHomepage clyjGoodsHomepage = selectList2.get(0);
                //根据规格id获取规格
                QueryWrapper<ClyjGoodsSpec> w3 = new QueryWrapper<ClyjGoodsSpec>();
                String specId = clyjShoppingCart.getSpecId();
                w3.eq("spec_id", specId);
                List<ClyjGoodsSpec> selectList3 = specService.selectList(w3);
                if (selectList3.size() == 0) {
                    continue;
                }
                clyjGoodsHomepage.setSpecVo(selectList3.get(0));
                clyjShoppingCart.setGoodsVo(clyjGoodsHomepage);
            }
            resultMap.put("code", "success");
            resultMap.put("cartData", selectList);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }

    /**
     * 清空购物车
     *
     * @param params
     * @return
     */
    @RequestMapping("/clearCart")
    @ResponseBody
    public Map<String, Object> clearCart(@RequestBody JSONObject params) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String token = params.getString("token");
        if (token == null || token.equals("")) {
            resultMap.put("code", "fail");
            resultMap.put("msg", "请先登录");
            return resultMap;
        }
        ClyjUser clyjUser = tokenUtils.Itoken(token);
        if (clyjUser == null) {
            resultMap.put("code", "fail");
            resultMap.put("msg", "登录已过期");
            return resultMap;
        }
        //获取当前用户id
        String userId = clyjUser.getUserId();
        //购物车类型
        String cartType = params.getString("cartType");
        //店铺id
        String shopId = params.getString("shopId");
        try {
            QueryWrapper<ClyjShoppingCart> w = new QueryWrapper<ClyjShoppingCart>();
            if (cartType == null || cartType == "") {
                resultMap.put("code", "fail");
                resultMap.put("msg", "购物车类型不能为空");
                return resultMap;
            }
            if (cartType.equals("2") && (shopId == null || shopId.equals(""))) {
                resultMap.put("code", "fail");
                resultMap.put("msg", "店铺id不能为空");
                return resultMap;
            }
            if (cartType.equals("2")) {
                w.eq("shop_id", shopId);
            }
            //根据用户id和商品id查询购物车表
            w.eq("user_id", userId);
            w.eq("cart_type", cartType);
            cartService.delete(w);
            resultMap.put("code", "success");
            resultMap.put("msg", "清空成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }
}